<?php
class App_Validate_Authorise extends Zend_Validate_Abstract
{
	const NOT_AUTHORISED = 'notAuthorised';
	protected $_messageTemplates = array(self::NOT_AUTHORISED => 'User + Password pair not found');
	protected $_authAdapter;
	public function isValid($value, $context = null)
	{
		$this->_setValue((string)$value);
		if(is_array($context)){
			if(!isset($context['password'])){
				return false;
			}
		}
		//$db = Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('db');
		$dbAdapter = Zend_Registry::get('db');
		$this->_authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$this->_authAdapter->setTableName('user')
				->setIdentityColumn('name')
				->setCredentialColumn('password')
				->setCredentialTreatment('SHA1(?)')
				->setIdentity($value)
				->setCredential($context['password']);
		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($this->_authAdapter);
		if(!$result->isValid()){
			$this->_error(self::NOT_AUTHORISED);
			return false;
		}
		else{
			$data = $this->_authAdapter->getResultRowObject(null, 'password');
			$auth->getStorage()->write($data);
			return true;
		}
		
	}
}